package com.icexxx.xlsexport;

import java.util.ArrayList;
import java.util.List;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;

/**
 * Excel工具类
 * 
 * @author iceroot
 * @since 1.0.0
 */
public class IceXlsExport {
	/**
	 * Excel导出
	 * 
	 * @param data 需要导出的数据
	 * @param file 文件路径
	 * 
	 * @since 1.0.0
	 */
	public static void write(List<List<String>> data, String file) {
		ExcelWriter writer = ExcelUtil.getWriter(file);
		writer.write(data);
		writer.close();
	}

	/**
	 * Excel导入
	 * 
	 * @param file 文件路径
	 * @return 读取到的数据
	 * 
	 * @since 1.0.0
	 */
	public static List<List<String>> read(String file) {
		ExcelReader reader = ExcelUtil.getReader(file);
		List<List<Object>> data = reader.read();
		return convertList(data);
	}

	private static List<List<String>> convertList(List<List<Object>> data) {
		List<List<String>> list = new ArrayList<>();
		for (int i = 0; i < data.size(); i++) {
			List<Object> rowData = data.get(i);
			List<String> row = new ArrayList<>();
			for (int j = 0; j < rowData.size(); j++) {
				Object object = rowData.get(j);
				String text = "";
				if (object != null) {
					text = String.valueOf(object);
				}
				row.add(text);
			}
			list.add(row);
		}
		return list;
	}

	/**
	 * 创建数据行
	 * 
	 * @param data 需要创建的数据行
	 * @return 创建好的集合
	 * 
	 * @since 1.0.0
	 */
	public static List<String> row(String... data) {
		List<String> list = new ArrayList<>();
		for (int i = 0; i < data.length; i++) {
			if (data[i] == null) {
				list.add("");
			} else {
				list.add(data[i]);
			}
		}
		return list;
	}

}
